package menu

import (
	"community-service/cmd/api/internal/models/model"
	"context"
	"fmt"
	"gorm.io/gorm"

	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"google.golang.org/grpc/codes"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetMenuLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMenuLogic {
	return &GetMenuLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetMenuLogic) GetMenu(req *types.MenuReq) (*types.MenuRsp, error) {

	var resp types.MenuRsp
	query := l.svcCtx.DB.WithContext(l.ctx)

	// 根据ID查询专栏
	if err := query.Model(&model.CsCommunityMenu{}).
		Session(&gorm.Session{}).Where("id = ?", req.Id).Find(&resp).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if resp.Id == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.MenuNotFound)
	}

	if err := query.Model(&model.CsCommunityTopic{}).
		Joins("topic").
		Joins(fmt.Sprintf("LEFT JOIN %s post ON post.topic_id = topic.id", model.TableNameCsCommunityPost)).
		Select(
			"topic.id", "topic.name", "topic.image_url", "topic.description",
			"topic.type", "topic.menu_id", "IFNULL(SUM(post.view_count), 0) view_count",
		).
		Where("menu_id = ?", req.Id).Find(&resp.Topics).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &resp, nil
}
